package com.coder.rental.service.impl;

import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.coder.rental.config.OSSConfig;
import com.coder.rental.service.IOssService;
import com.coder.rental.utils.FilesUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@Service
public class OssServiceImpl implements IOssService {
    @Resource
    private OSSConfig ossConfig;
    /**
     * 上传文件到OSS存储
     * @param file 要上传的文件
     * @return 文件访问URL地址
     */
    @Override
    public String upload(MultipartFile file) {
        // 获取原始文件名并生成新的文件名
        String originalFilename = file.getOriginalFilename();
        String fileName = FilesUtils.getFileName(originalFilename);

        // 创建OSS客户端连接
        OSS ossClient=new OSSClientBuilder().build(ossConfig.getEndpoint(),
                ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
        try {
            // 上传文件到OSS
            ossClient.putObject(ossConfig.getBucketName(),fileName,file.getInputStream());
            // 构造并返回文件访问URL
            return "https://"+ossConfig.getBucketName()+"."+ossConfig.getEndpoint()+"/"+fileName;
        }catch (Exception e){
            throw new RuntimeException("上传失败");
        }finally {
            // 关闭OSS客户端连接
            if(ossClient != null){
                ossClient.shutdown();
            }
        }
    }

    /**
     * 从OSS存储删除文件
     * @param url 要删除的文件URL地址
     * @return 删除结果标识
     */
    @Override
    public boolean delete(String url) {
        // 创建OSS客户端连接
        OSS ossClient=new OSSClientBuilder().build(ossConfig.getEndpoint(),
                ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());

        // 构造OSS存储中的对象名称
        String host="https://"+ossConfig.getBucketName()+"."+ossConfig.getEndpoint()+"/";
        String objectName= StrUtil.removePrefix(url,host);
        try {
            // 从OSS删除指定对象
            ossClient.deleteObject(ossConfig.getBucketName(),objectName);
        }catch (Exception e){
            throw new RuntimeException("删除失败");
        }finally {
            // 关闭OSS客户端连接
            if(ossClient != null){
                ossClient.shutdown();
            }
        }
        return false;
    }
}

